package com.example.basic.handler;

import com.fasterxml.jackson.core.JsonParseException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalJacksonExceptionHandler {

    /**
     * 处理 JsonParseException
     * @param ex 异常对象
     * @return 响应实体
     */
    @ExceptionHandler(JsonParseException.class)
    @ResponseBody
    public ResponseEntity<String> handleJsonParseException(JsonParseException ex) {
        String errorMessage = "请求格式不合法，请检查";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON); // 设置Content-Type为application/json
        headers.add("Content-Type", "application/json; charset=UTF-8"); // 手动添加charset=UTF-8
        System.out.println("errorMessage--------->" + errorMessage);
        return new ResponseEntity<>(errorMessage, headers, HttpStatus.BAD_REQUEST);
    }

}
